import { useRequest } from 'ahooks';
import { Button, Divider, Empty, Form, Input, Spin, Typography } from 'antd';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';

import SourceCode, { PrismCode } from '@/components/SourceCode';
import { VulnerableProps } from '@/components/VulnerableTemplate/type';
import burstCode from '@/pages/vulnerable/code/burst';

import { dangerousLogin } from '../../service';

const { Title } = Typography;

const codeProps: PrismCode = {
  language: 'tsx',
  code: burstCode.normal,
};

const Vulnerable: React.FC = () => {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const [shell, setShell] = useState<string>('');

  const { run, loading } = useRequest(
    async () => {
      const params = form.getFieldsValue();
      await dangerousLogin(params)
        .then(res => {
          setShell(JSON.stringify(res, null, '\t'));
        })
        .catch(err => {
          setShell(JSON.stringify(err.response.data, null, '\t'));
        });
    },
    { manual: true },
  );

  return (
    <div className="flex ldpi:flex-col">
      <Form
        className="flex-1 pr-4"
        layout="vertical"
        form={form}
        labelAlign="left"
        labelCol={{ span: 4 }}
      >
        <Form.Item name="username" label={t('username')}>
          <Input placeholder={t('usernamePlaceholder') as string} />
        </Form.Item>
        <Form.Item name="password" label={t('password')}>
          <Input placeholder={t('passwordPlaceholder') as string} />
        </Form.Item>
        <Button onClick={run}>{t('SIGNIN')}</Button>
      </Form>
      <Divider className="ldpi:block hdpi:hidden" />
      <section className="flex-1 overflow-scroll">
        <Title italic level={4}>
          {t('result')}
        </Title>
        <Spin spinning={loading}>
          {shell !== '' ? (
            <SourceCode
              className="border border-[#e5e7eb] overflow-scroll"
              language="bash"
              code={shell}
            />
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={t('empty')} />
          )}
        </Spin>
      </section>
    </div>
  );
};

const BurstNormal: VulnerableProps = {
  vulnerable: <Vulnerable />,
  codeProps,
  causesSolutions: {
    type: 'burst',
    hasCompare: false,
    solutions: 3,
  },
};

export default BurstNormal;
